#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "Music_Library.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    timer = new QTimer();
    timer->setInterval(2000);
    timer->start();

}





MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_b1_clicked()
{
    if(QMediaPlayer::PlayingState == player.state())
    {
        player.pause();
        ui->b1->setText("Play");
    }
    else
    {
        player.play();
        ui->b1->setText("Pause");
    }

}

void MainWindow::on_Slider1_sliderMoved(int position)
{
    // 文件的总帧数: player.duration()
    // position 滑动条当前位置
    // setPosition: 设置播放进度的位置
    player.setPosition(player.duration()*position/100);
}

void MainWindow::setSliderValue()
{
    // 与上函数逆过程
    // position() const  获取当前的播放进度位置（以毫秒为单位）。

    ui->Slider1->setValue(player.position()*100/player.duration());
}

void MainWindow::on_Slider2_sliderMoved(int position)
{
    player.setVolume(position);
}

void MainWindow::on_AddMusic_clicked()
{
    QString fileName = QFileDialog::getExistingDirectory(NULL,"Select Music Dir",".",NULL);
    QDir dir(fileName);
    QStringList nameFilters;
    nameFilters << "*.mp3";
    QStringList files = dir.entryList(nameFilters, QDir::Files|QDir::Readable, QDir::Name);
    ui->MusicList->addItems(files);
    playPath = fileName;

}

void MainWindow::on_MusicList_itemDoubleClicked(QListWidgetItem *item)
{
    PlayRow = ui->MusicList->row(item);
    player.stop();
    player.setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player.play();
    ui->Slider1->setValue(player.position());
    connect(timer, SIGNAL(timeout()), this, SLOT(setSliderValue()));
}

void MainWindow::on_b2_clicked()
{
    if(PlayRow == 0){
        PlayRow = ui->MusicList->count() - 1;
    }
    else{
        PlayRow--;
    }
    QListWidgetItem *item = ui->MusicList->item(PlayRow);
    item->setSelected(true);
    player.stop();
    player.setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player.play();

}

void MainWindow::on_b3_clicked()
{
    if(PlayRow + 1 == ui->MusicList->count()){
        PlayRow = 0;
    }
    else{
        PlayRow++;
    }
    QListWidgetItem *item = ui->MusicList->item(PlayRow);
    item->setSelected(true);
    player.stop();
    player.setMedia(QUrl::fromLocalFile(playPath+"/"+item->text()));
    player.play();
}
